<?php

namespace Pinenut\Files;

use Pinenut\Model2\Embedded;

/**
 * Описание файла - его имя (идентификатор), когда создан, тип, размер и хэш
 * 
 * @author kosh
 *
 */
class File extends Embedded {

	public $id;
	public $created;
	public $mimeType;
	public $size;
	public $md5;
	static function fields() {
		return array_merge ( parent::fields (), [ 
				'id' => static::STRING,
				'created' => static::DATE,
				'mimeType' => static::STRING,
				'size' => static::INT,
				'md5' => static::STRING
		] );
	}
	

	/**
	 * Внедряем зависимости
	 */
	use \Pinenut\Di\Injectable;
	
	
	/**
	 * @var \Pinenut\Files\Adapter
	 */
	
	protected $_fileAdapter;
	/**
	 * @var \Pinenut\Files\Adapter
	 */
	static protected $_fileAdapterClass;
	

	/**
	 *
	 * @return \Pinenut\Files\Adapter
	 */
	function getFileAdapter() {
		if (!$this->_fileAdapter) {
			$class = static::$_fileAdapterClass;
			$this->_fileAdapter = new $class();
		}
	
		return $this->_fileAdapter;
	}
	
	
	function putFile($filename) {
		// определяем тип и размер
		$this->size = filesize($filename);
		$mimetype = exec('file -i -b '.escapeshellarg($filename));
		if (strpos($mimetype, ';')) {
			list ($mimetype, $charset) = explode(';', $mimetype);
		}
		$this->mimeType = $mimetype;
		
		$this->md5 = md5_file($filename);
		
		$this->created = time();
		
		return $this->id = $this->getFileAdapter()->putFile($filename);
	}
	
	function getBytes() {
		return $this->getFileAdapter()->get($this->id);
	}
}